/*freshfresh attachment widget*/
openerp.attachment_widget = function(instance) {
	var _t = instance.web._t, _lt = instance.web._lt;
	var QWeb = instance.web.qweb;
    instance.attachment_widget = {};

	instance.attachment_widget.file_widget = instance.web.form.AbstractField.extend({
		editBar: '<div id="ff-del">' +
			'<span class="img-del"><img src="/attachment_widget/static/src/images/del.png" /></span>' +
			'<div style="clear:both;"></div></div>',
		init: function(a, b) {
			this._super.apply(this, arguments);
			this.set("value", "");
			this.limitType = b.attrs.limittype == undefined ? []: b.attrs.limittype.split(',');
		},
		start: function() {
			this.display_field();

			this.on("change:effective_readonly", this, function() {
				this.render_value();
			});

			return this._super();
		},
		display_field : function() {
			this.$el.html(QWeb.render("ff_file_widget", {
				widget : this
			}));
		},
		fileChange: function(){
			var self = this;
			$('#newfile').unbind();
			$('#newfile').change(function(){
			    var ext = $('#newfile').val().split('.').reverse()[0];
                if (self.limitType.length>0){
                    if($.inArray(ext, self.limitType)==-1){
                        alert('只接受以下文件类型，'+self.limitType.join(','))
                        return;
                    };
                };
                self.fileUpload();
            });
		},
		fileUpload: function(){
		    if(this.view.datarecord.id==undefined){
		        alert("请先保存form，在进行编辑添加附件");
		        return false;
		    };
			var self = this;
			$("#progress-img")
	        .ajaxStart(function(){
	        	src = $(this).attr("src");
	            $(this).attr("src","/web/static/src/img/throbber.gif");
	        }).ajaxComplete(function(){
	            $(this).attr("src","/attachment_widget/static/src/images/new-image.png");
				self.fileChange();
	        });

	        $.ajaxFileUpload
	        (
	            {
	                url:'/attachment_widget/addFile/',
	                secureuri:false,
	                data: { model: this.view.model, id: this.view.datarecord.id },
	                fileElementId:'newfile',
	                dataType: 'json',
	                success: function (data, status){
                        if(data.state == 1)
                        {
                            var html = '';
                            if (data.data.file_type_icon!='webimage'){
                                html += "<div class='oe_attachment oe_ff' data-id='"+data.data.attId+"'>";
                                html += "    <a href='/mail/download_attachment?model="+data.data.parentModel+"&id="+data.data.parendId+"&method=download_attachment&attachment_id="+data.data.attId+"' target='_blank'>";
                                html += "   <img src='/mail/static/src/img/mimetypes/"+data.data.attIcon+".png' />";
                                html += "   <div class='oe_name' style='word-break: break-all;'>"+data.data.filename+"</div>";
                                html += "</a></div>";
                            }else{
                                html += "<div class='oe_attachment oe_ff oe_preview' data-id='"+data.data.attId+"'><a href='/mail/download_attachment?model="+data.data.parentModel+"&id="+data.data.parendId+"&method=download_attachment&attachment_id="+data.data.attId+"' target='_blank'>";
                                html += "<img src='/web/binary/image?model=ir.attachment&field=datas&id="+data.data.attId+"&resize=100%%252C80' />";
                                html += "<div class='oe_name' style='word-break: break-all;'>"+data.data.filename+"</div>";
                                html += "</a></div>";
                            };
                            self.createNewFile(html);
                        }else{
                            alert('无返回信息');
                        }
	                },
	                error: function (data, status, e){
	                    console.log("err",e);
	                }
	            }
	        )
		},
		createNewFile: function(html){
			$("#add-file").parent().prepend( html );
			this.editActivate();
		},
		editActivate: function(){
			var self = this;

            this.$("#ff_file_widget_id div.oe_ff").unbind("mouseover");
			this.$("#ff_file_widget_id div.oe_ff").mouseover(function(){
				if ($("#ff-del").length == 0){
					$(this).prepend($(self.editBar));
				}
			});

            this.$("#ff_file_widget_id div.oe_ff").unbind("mouseleave");
			this.$("#ff_file_widget_id div.oe_ff").mouseleave(function(){
				if ($("#ff-del").length > 0){
					$(this).find("#ff-del").remove();
				}
			});

			this.$("#ff_file_widget_id #add-file img").click(function(){
				$(this).parent().find("#newfile").trigger("click");
			});

			this.$("#ff_file_widget_id .img-del").live('click', function(){
				var obj = $(this).parent().parent();
				var id = parseInt(obj.attr("data-id"));
				ds_attachment = new instance.web.DataSetSearch(this, self.view.model);
				ds_attachment.unlink([id]);
				obj.remove();
			});
		},
		render_value: function() {
			var self = this;

			var html = '<div class="oe_msg_attachment_list">';
			var attData = this.get("value");
			if ( attData.length>0 ){
				for (var i = 0; i<attData.length; i++){
					html += attData[i].html;
				};
			};
			if (!this.get("effective_readonly")) {
				html += '<div id="add-file" class="oe_attachment"><input type="file" id="newfile" name="newfile" /><img id="progress-img" src="/attachment_widget/static/src/images/new-image.png" /></div>';
			};
			this.$("#ff_file_widget_id").html(html+'</div>');
			
			//////////////////////////
			if (!this.get("effective_readonly")) {
				this.editActivate();
				self.fileChange();
			};
		}
	});

	instance.web.form.widgets.add('ff_file_widget', 'instance.attachment_widget.file_widget');
};